<template>
  <div>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        class="-mb-15px"
        label-width="68px"
      >
        <el-form-item label="查询条件" prop="name">
          <el-input
            v-model="queryParams.name"
            class="!w-260px"
            clearable
            placeholder="请输入名称或者厂家或者型号或者参数"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="防护类型" prop="type">
          <el-select
            v-model="queryParams.type"
            :disabled="disableTypeSelect"
            class="!w-240px"
            clearable
            placeholder="请选择防护类型"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.GEAR_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon class="mr-5px" icon="ep:search" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon class="mr-5px" icon="ep:refresh" /> 重置</el-button>
          <el-button
            v-hasPermi="['system:protect-gear:create']"
            plain
            type="primary"
            @click="openForm('create')"
          >
            <Icon class="mr-5px" icon="ep:plus" /> 新增
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap v-if="!props.defaultType">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="list"
        :show-overflow-tooltip="true"
        :stripe="true"
      >
        <el-table-column align="center" label="序号" type="index" width="60" />
        <el-table-column align="center" label="名称" prop="name" />
        <el-table-column align="center" label="防护类型" prop="type">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.GEAR_TYPE" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="生产厂家" prop="manufacturer" />
        <el-table-column align="center" label="型号" prop="model" />
        <el-table-column align="center" label="参数" prop="parameter" />
        <el-table-column
          :formatter="dateFormatter"
          align="center"
          label="创建时间"
          prop="createTime"
          width="180px"
        />
        <el-table-column align="center" label="操作" min-width="120px">
          <template #default="scope">
            <el-button
              v-hasPermi="['system:protect-gear:update']"
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              v-hasPermi="['system:protect-gear:delete']"
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 已选择和已有防护区域 -->
    <ContentWrap v-if="props.defaultType">
      <!-- 已选择的防护设备区域 -->
      <div class="selected-area">
        <div class="area-title">已选择的防护:</div>
        <div class="selected-items">
          <el-tag
            v-for="item in selectedItems"
            :key="item.id"
            class="mx-5px my-5px"
            closable
            @close="handleRemoveSelected(item)"
          >
            {{ item.name }}
          </el-tag>
        </div>
      </div>

      <!-- 已有的防护设备区域 -->
      <div class="selected-area mt-15px">
        <div class="area-title">防护列表:</div>
        <div class="selected-items">
          <el-tag
            v-for="item in list"
            :key="item.id"
            class="mx-5px my-5px"
            type="success"
            @click="handleSelectItem(item)"
          >
            {{ item.name }}
          </el-tag>
        </div>
      </div>
      <!-- 底部操作栏 -->
    </ContentWrap>
    <!-- 表单弹窗：添加/修改 -->
    <ProtectGearForm ref="formRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { ProtectGearApi, ProtectGearVO } from '@/api/system/protectgear'
import ProtectGearForm from './ProtectGearForm.vue'
import { PropType } from 'vue'

/** 防护装备 列表 */
defineOptions({ name: 'ProtectGear' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ProtectGearVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  type: undefined as number | undefined,
  manufacturer: undefined,
  model: undefined,
  parameter: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 定义组件属性
const props = defineProps({
  defaultType: {
    type: Number as PropType<number | undefined>,
    default: undefined
  },
  disableTypeSelect: {
    type: Boolean,
    default: false
  },
  existingProtections: {
    type: Array as PropType<ProtectGearVO[]>,
    default: () => []
  }
})

// 定义 emit
const emit = defineEmits(['select', 'cancel'])

// 使用 ref 替代 Map 来管理选中项
const selectedItems = ref<ProtectGearVO[]>([])

// 清空选中状态的方法
const clearSelected = () => {
  selectedItems.value = []
}

// 移除已选择项的处理函数
const handleRemoveSelected = (item: ProtectGearVO) => {
  selectedItems.value = selectedItems.value.filter((i) => i.id !== item.id)
}

// 选择项目的处理函数
const handleSelectItem = (item: ProtectGearVO) => {
  // 检查是否已经选择过
  const isSelected = selectedItems.value.some((selected) => selected.id === item.id)
  if (!isSelected) {
    selectedItems.value.push(item)
  }
}

// 添加一个防抖标志
let isLoadingData = false

// 工具函数：提取对象中的 id 和 name
const formatLogData = (data: any) => {
  if (Array.isArray(data)) {
    return data.map((item) => ({ id: item.id, name: item.name }))
  }
  return { id: data.id, name: data.name }
}

// 修改表格选择变化处理

// 修改 getList 方法
const getList = async () => {
  if (isLoadingData) {
    return
  }

  isLoadingData = true
  loading.value = true

  try {
    // 根据是否是弹窗模式来设置不同的分页大小
    const params = {
      ...queryParams,
      pageSize: props.defaultType ? 999 : queryParams.pageSize
    }

    const data = await ProtectGearApi.getProtectGearPage(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
    isLoadingData = false
  }
}

// 修改预选方法
const preSelect = async (items: { name: string; id: number | null }[]) => {
  selectedItems.value = items
    .filter((item): item is { name: string; id: number } => item.id !== null)
    .map((item) => ({ id: item.id, name: item.name }) as ProtectGearVO)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  console.log('===== Reset Query Start =====')
  console.log(
    '重置前全局选中:',
    JSON.stringify(formatLogData(Array.from(selectedItems.value)), null, 2)
  )

  queryFormRef.value.resetFields()
  selectedItems.value = []

  console.log(
    '重置后全局选中:',
    JSON.stringify(formatLogData(Array.from(selectedItems.value)), null, 2)
  )
  console.log('===== Reset Query End =====\n')

  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProtectGearApi.deleteProtectGear(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  if (props.defaultType) {
    queryParams.type = props.defaultType
  }
  // 只在没有预选项时调用 getList
  if (!props.showCheckbox) {
    getList()
  }
})

// 添加获取选中项的方法
const getSelectedItems = () => {
  return selectedItems.value
}

// 暴露方法给父组件
defineExpose({
  clearSelected,
  preSelect,
  getSelectedItems
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  padding: 0px 0 0;
  text-align: left;
}

.selected-area {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;

  .area-title {
    font-weight: bold;
    margin-bottom: 10px;
    color: #606266;
  }

  .selected-items {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
  }
}

.mt-15px {
  margin-top: 15px;
}

.mx-5px {
  margin: 0 5px;
}

.my-5px {
  margin: 5px 0;
}

.selected-items {
  .el-tag {
    cursor: pointer; // 添加鼠标指针样式
    transition: all 0.3s; // 添加过渡效果

    &:hover {
      opacity: 0.8;
    }
  }
}
</style>
